package com.chaudcast;

/**
 * Various utility methods.
 */
public class Util {

	public static String getHost(String locator) {		
		// remove protocol from URL
		if (locator.indexOf("://")!=-1) {
			locator = locator.substring(locator.indexOf("://")+3);
		}
		
		// remove port from URL
		if (locator.indexOf(':') != -1) {
			locator = locator.substring(0,locator.indexOf(':'));
		}
		
		// remove URI from URL
		if (locator.indexOf('/')!=-1) {
			locator = locator.substring(0,locator.indexOf('/'));
		}
		
		return locator;
	}
	
	public static int getPort(String locator) {
		int port = 80; // default HTTP port
		int beginPosition;
		int endPosition;
		
		// remove protocol from URL
		if (locator.startsWith("https://")) {
			port = 443; // default SSL port
			locator = locator.substring(locator.indexOf("https://")+8);
		} else if (locator.indexOf("://") != -1) {
			locator = locator.substring(locator.indexOf("://")+3);
		}
		
		beginPosition = locator.indexOf(':');
		endPosition = locator.indexOf('/', beginPosition);
		if (endPosition == -1) {
			// port goes till the end of the string
			endPosition = locator.length();
		}
			try {
				port = Integer.parseInt(locator.substring(beginPosition+1, endPosition));
			} catch (NumberFormatException nfe) {
				// the port is not valid, assume default
			}
		
		return port;
	}
	
	public static String getUri(String locator) {

		// remove protocol from URL
		if (locator.indexOf("://")!=-1) {
			locator = locator.substring(locator.indexOf("://")+3);
		}
		
		// remove host and port and add default URI if necessary
		if (locator.indexOf('/') != -1) {
			locator = locator.substring(locator.indexOf('/'));
		} else {
			locator = "/";
		}
		
		return locator;
	}
}
